Ext.define('Ext.ux.CheckboxStoreGroup', {
    extend: 'Ext.form.CheckboxGroup',
    alias: 'widget.checkboxstoregroup',
    config: {
        store: null,
        labelField: 'label',
        valueField: 'id',
        checkedField: 'checked',
        columns: 3,
        boxFieldName: 'mycheckbox'
    },
    applyStore: function(store) {
        if (Ext.isString(store)) {
            return Ext.getStore(store);
        } else {
            return store;
        }
    },
    updateStore: function(newStore, oldStore) {
        if (oldStore) {
            store.removeEventListener('datachanged', this.onStoreChange, this)
        }
        newStore.on('datachanged', this.onStoreChange, this);
    },
    onStoreChange: function(s) {
        Ext.suspendLayouts();
        this.removeAll();

        var vField = this.getValueField();
        var lField = this.getLabelField();
        var cField = this.getCheckedField();
        var fName = this.getBoxFieldName();
        var rec = null;

        for (var i=0; i<s.getCount(); i++) {
        	rec = s.getAt(i);
        	var inputValue = rec.get(vField);
        	var checked = rec.get(cField);
        	
        	var selval = s.config.selval;
        	if(selval) {
        		var arr = selval.split(',');
        		if(Ext.Array.contains(arr, inputValue+'')) {
        			checked = true;
        		}
        	}
            
            this.add({
                xtype: 'checkbox',
                inputValue: inputValue,
                boxLabel: rec.get(lField),
                checked: checked,
                name: fName
            });
        }

        Ext.resumeLayouts(true);

    }, 
    initComponent: function() {
        this.callParent(arguments);
        this.on('afterrender', this.onAfterRender);
    },
    onAfterRender: function() {
        if (this.getStore().totalCount) {
            this.onStoreChange(this.getStore());
        }
    }
});